package com.wwk.phone.controller;

import com.wwk.phone.entity.User;
import com.wwk.phone.exceptionhandler.MyException;
import com.wwk.phone.service.UserService;
import com.wwk.phone.utils.JwtUtils;
import com.wwk.phone.utils.R;
import com.wwk.phone.utils.ResultCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * ResponseEntity.ok().body("登录成功"), 返回状态码和数据
 *
 * @author wwk
 * @since 2023/6/5
 */
@RestController
@RequestMapping("user")
@CrossOrigin(allowCredentials = "true")
public class LoginController {
    @Autowired
    private UserService userService;

    @PostMapping("login")
    public R login(@RequestBody User user) {
        System.out.println("登录方法");
        user = userService.checkUser(user.getUsername(), user.getPassword());
        String jwtToken = "";
        if (user != null) {
            jwtToken = JwtUtils.getJwtToken(String.valueOf(user.getId()), user.getUsername());
        } else {
            throw new MyException(ResultCode.ERROR, "用户校验失败");
        }
        //能正常获取到token
        System.out.println(JwtUtils.checkToken(jwtToken));
        return R.ok().data("token", jwtToken);
    }

    @GetMapping("info")
    public R Info(HttpServletRequest request) {
        if (!JwtUtils.checkToken(request)) {
            throw new MyException(ResultCode.ERROR, "token异常");
        }
        //通过jwt获取用户id
        String id = JwtUtils.getMemberIdByJwtToken(request);
        User user = userService.queryById(Long.valueOf(id));
        return R.ok().data("roles", "[admin]").data("name", user.getUsername()).data("id", user.getId()).data("avatar", "http://plutoc.icu/images/me.jpg");
    }

    @PostMapping("logout")
    public R logout() {
        return R.ok().message("退出成功");
    }
}
